package com.google.code.irouter.portal.server;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.code.irouter.model.Consumer;
import com.google.code.irouter.model.Model;
import com.google.code.irouter.model.Relationship;
import com.google.code.irouter.model.Transponder;
import com.google.code.irouter.portal.client.rpc.consumer.ConsumerResult;
import com.google.code.irouter.portal.client.rpc.transponder.TransponderResult;
import com.google.code.irouter.portal.client.rpc.transponder.TransponderService;
import com.google.code.irouter.utils.ModelUtil;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class TransponderServiceImpl extends RemoteServiceServlet implements TransponderService {

	private static final long serialVersionUID = -7656722233118311146L;

	@Override
	public TransponderResult get(String id) throws IllegalArgumentException {
		TransponderResult result = null;
		try {
			List<Model> relationList = ModelUtil.select(Relationship.class, KeyFactory.createKey(Relationship.class.getSimpleName(), Long.valueOf(id)));
			if(relationList.size() > 0) {
				Key transponderKey = ((Relationship) relationList.get(0)).getTransponder();
				List<Model> modelList = ModelUtil.select(Transponder.class, transponderKey);
				result = new TransponderResult();
				if(modelList.size() > 0) {					
					Transponder transponder = (Transponder) modelList.get(0);
					Set<Key> keySet = transponder.getConsumers();
					List<ConsumerResult> consumers = new ArrayList<ConsumerResult>();
					for(Key key : keySet) {
						List<Model> consumerList = ModelUtil.select(Consumer.class, key);
						if(consumerList.size() > 0) {
							Consumer consumer = (Consumer) consumerList.get(0);
							ConsumerResult consumerResult = new ConsumerResult();
							consumerResult.setId(consumer.getKey().getId());
							consumerResult.setName(consumer.getName());
							consumerResult.setOwner(consumer.getOwner());
							consumerResult.setSender(ConsumerServiceImpl.getSenderName(consumer.getSender()));
							consumerResult.setConsumerKey(consumer.getConsumerKey());
							consumerResult.setConsumerSecret(consumer.getConsumerSecret());
							consumerResult.setUser(consumer.getUser());
							consumerResult.setMaxLength(consumer.getMaxLength());
							consumers.add(consumerResult);
						}
					}
					result.setConsumers(consumers);
				}
			}			
		} catch (Exception exception) {
			// TODO
		}
		return result;
	}
}
